/* eslint-disable vue/no-template-shadow */
<template>
  <a-modal
    title="编辑隐患信息"
    :width="1400"
    :maxHeight="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    style="margin-top: -40px"
  >
    <a-spin :spinning="confirmLoading">
      <a-divider orientation="left" style="font-weight: bold; margin-top: -10px" >
        <a-icon type="profile" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon>基本信息
      </a-divider>
      <a-row :gutter="24">
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['qhseXyDangerId']" />
            </a-form-item>
            <a-form-item
              label="检查人员"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input placeholder="请输入检查人员" v-decorator="['checkName',{ rules:[{ required: true, message: '请输入检查人员！'}]}]" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="检查类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择检查类型" v-decorator="['checkType',{ rules:[{ required: true, message: '请选择检查类型！'}]}]" @change="choosecheckSpecialty(item)">
                <a-select-option v-for="item in checkSpecialData" :key="item.id" :value="item.item">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="检查时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-date-picker
                placeholder="选择日期"
                show-time
                :showToday="true"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="checkTime"
                @change="handleChangeTime"/>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-select allow-clear placeholder="请选择数据来源" v-decorator="['enterSys']">
                <!-- <a-select-option v-for="(item) in workSpecialData" :key="item.id" :value="item.specialty" @click="chooseWorkSpecialty(item)">{{ item.specialty }}</a-select-option> -->
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form" >
            <a-form-item
              label="录入时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input v-decorator="['enterTime']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="属地单位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-tree-select
                v-model="organizationName"
                allowClear
                showSearch
                tree-node-filter-prop="title"
                :treeData="QHSEOrganizationTree"
                v-if="QHSEOrganizationTree.length"
                :defaultExpandAll="true"
                :replaceFields="replaceFields"
                placeholder="请选择属地单位"
                @change="handleOrganizationSelectChange"
                :title="organizationName"
              >
              </a-tree-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="发包单位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-tree-select
                v-model="contractingUnitName"
                allowClear
                showSearch
                style="width: 100%;"
                tree-node-filter-prop="title"
                :treeData="unitTree"
                v-if="unitTree.length"
                :defaultExpandAll="true"
                :replaceFields="replaceFields"
                placeholder="请选择发包单位"
                @change="handlefbOrganizationSelectChange"
                :title="contractingUnitName"
              >
              </a-tree-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="作业专业"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择作业专业" v-decorator="['workSpecialty',{ rules:[{ required: true, message: '请选择作业专业！'}]}]" @change="handleZYZYSelectChange">
                <a-select-option v-for="item in QHSEKeyWorkSpecialtyList" :key="item.id" :value="item.specialty" :code="item.specialtyCode">{{
                  item.specialty
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['workSpecialtyCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="作业项目"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input placeholder="请输入作业项目" v-decorator="['workItem',{ rules:[{ message: '请输入作业项目！'}]}]"/>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-divider orientation="left" style="font-weight: bold; margin-top: -10px">
        <a-icon type="info-circle" style="margin-right: 8px; color:rgb(13, 158, 243);"></a-icon> 关键作业信息
      </a-divider>
      <a-row :gutter="24">
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="关键作业类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-select allow-clear placeholder="请选择关键作业类型" v-decorator="['workType']" @change="handleKeyWorkTypeSelectChange">
                <a-select-option v-for="item in KeyWorkTypeList" :key="item.id" :value="item.workType" :code="item.workTypeCode">{{
                  item.workType
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['keyWorkCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="12">
          <a-form :form="form">
            <a-form-item
              label="关键作业内容"
              :labelCol="{ sm: { span: 4 } }"
              :wrapperCol="{ sm: { span: 20 } }"
            >
              <a-select allow-clear show-search placeholder="请选择关键作业内容" v-decorator="['workContent']" @change="handleKeyWorkContentSelectChange">
                <a-select-option v-for="item in KeyWorkContentList" :key="item.id" :value="item.workContent" :rk="item.workRisk">{{
                  item.workContent
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="作业风险等级"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input placeholder="请输入作业风险等级" v-decorator="['workRisk']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-divider orientation="left" style="font-weight: bold; margin-top: -10px">
        <a-icon type="alert" style="margin-right: 8px;color:rgb(13, 158, 243);"></a-icon> 隐患信息
      </a-divider>
      <a-row :gutter="24">
        <a-col :span="18" >
          <a-form :form="form">
            <a-form-item
              label="隐患条款"
              :labelCol="labelCol_A"
              :wrapperCol="wrapperCol_A"
              style="width: 107.2%; margin-left: -27px"
              required
            >
              <a-select allow-clear show-search placeholder="请输入关键字段选择隐患条款" v-decorator="['dangerClause',{ rules:[{ required: true, message: '请输入关键字段选择隐患条款！'}]}]">
                <a-select-option v-for="item in dangerClauseList" :key="item.id" :value="item.description" @click="chooseDangerClause(item)">{{
                  item.description
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
            >
              <a-radio-group v-decorator="['dangerTypeCategory',{ rules:[{ required: true, message: '请选择隐患类型！'}]}]" @change="handleDangerRadioChange">
                <a-radio value="通用隐患" style="margin-left: 20px">通用隐患</a-radio>
                <a-radio value="专业隐患" style="margin-left: -10px">专业隐患</a-radio>
                <a-radio value="其他" style="margin-left: -10px">其他</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="18" >
          <a-form :form="form">
            <a-form-item
              label="隐患描述"
              :labelCol="labelCol_A"
              :wrapperCol="wrapperCol_A"
              style="width: 107.2%; margin-left: -28px"
              required
            >
              <a-textarea
                v-decorator="['description',{ rules:[{ required: true, message: '请输入隐患描述！'}]}]"
                placeholder="请输入隐患描述"
                :rows="2"
                :span="40"
              />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="8" >
          <a-form :form="form">
            <a-form-item
              label="隐患所属相关方公司"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input placeholder="请输入隐患所属相关方公司" v-decorator="['relatedCompany',{ rules:[{ required: true, message: '请输入隐患所属公司'}]}]"/>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="隐患级别"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择隐患级别" v-decorator="['dangerType',{ rules:[{ required: true, message: '请选择隐患级别！'}]}]" @change="handleDangerTypeSelectChange">
                <a-select-option v-for="(item) in HazardLevelList" :key="item.id" :value="item.item" :dtc="item.code">{{ item.item }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['dangerTypeCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="位置区域"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select v-decorator="['location',{ rules:[{ required: true, message: '请选择位置区域！'}]}]" allow-clear placeholder="请选择位置区域">
                <a-select-option v-for="item in LocationList" :key="item.id" :value="item.location">{{
                  item.location
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="隐患类别"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-tree-select
                v-model="dangerCategory"
                allowClear
                showSearch
                tree-node-filter-prop="title"
                v-if="QHSEDangerCategoryTree.length"
                :treeData="QHSEDangerCategoryTree"
                :defaultExpandAll="true"
                :replaceFields="replaceFields"
                placeholder="请选择隐患类别"
                @change="handleDangerCategorySelectChange"
                :title="dangerCategory"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['dangerCateId']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="对应体系要素"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <!-- <a-input placeholder="请选择对应要素体系" v-decorator="['hseElement']" disabled/> -->
              <a-select allow-clear placeholder="请选择对应体系要素" v-decorator="['hseElement']">
                <a-select-option v-for="item in dangerHSEList" :key="item.id" :value="item.item" @click="chooseHse(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['hseCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="原因分析"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select v-decorator="['causeAnalysis',{ rules:[{ required: true, message: '请选择原因分析！'}]}]" allow-clear placeholder="请选择原因分析">
                <a-select-option v-for="item in QHSEYYFXList" :key="item.id" :value="item.item" @click="chooseCause(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['clauseAnalysisCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <!-- <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="归属部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择归属部门" v-decorator="['directDepartment',{ rules:[{ required: true, message: '请选择归属部门！'}]}]">
                <a-select-option v-for="item in QHSEGSBMList" :key="item.id" :value="item.item" @click="chooseDepart(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['departmentCode']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['checkOrganizationId']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['userId']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['dangerPic']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['reformerPic']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['observeComm']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['potentialConsequence']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-model="organizationId" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['checkDate',{ rules:[{ required: true, message: '请选择检查时间！'}]}]" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['reformerDate']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['acceptanceDate']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['reformerUserId']" />
            </a-form-item>
          </a-form>
        </a-col> -->
        <a-col :span="15" style="margin-bottom: -57px">
          <a-form :form="form">
            <a-form-item label="隐患图片" :labelCol="labelCol_A" :wrapperCol="wrapperCol_A">
              <a-upload
                name="file"
                list-type="picture-card"
                :file-list="dangerFileList"
                :showUploadList="true"
                data-type="jpg|png|jpeg|JPG|PNG|JPEG"
                ref="Pics"
                :before-upload="beforeDangerUpload"
                @change="handleDangerPicChange"
                :remove="handleDangerRemove"
                @preview="handlePreview"
                :customRequest="customRequest"
                multiple
              >
                <div v-if="dangerShowLoader" class="spinner"></div>
                <div id="container" v-if="dangerFileList.length < 4 && !dangerShowLoader">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handlePicCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-divider orientation="left" style="font-weight: bold;">
        <a-icon type="tool" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon> 整改信息
      </a-divider>
      <a-row :gutter="24">
        <!-- <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="整改负责人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input
                suffix-icon="down"
                v-decorator="['reformerUserName']"
                @click="showModal"
                allow-clear
                read-only
                ref="input"
                placeholder="请选择整改人员姓名"/>
              <a-modal
                style="margin-top:-50px"
                @cancel="handleModalCancel"
                :visible="Modalvisible"
                :width="1300"
                :height="850"
              >
                <choose-people
                  :people-list="peopleList"
                  @cancel="handleModalCancel"
                  @chooseUser="chooseVioPeople"
                  :userId="reformerUserId"
                />
                <template #footer>
                  <a-button type="default" @click="handleModalCancel">取消</a-button>
                </template>
              </a-modal>
            </a-form-item>
          </a-form>
        </a-col> -->
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="限期整改时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-date-picker
                placeholder="选择日期"
                show-time
                :showToday="true"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="reformTime"
                @change="handleChangeTime2"/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="12" style="margin-bottom: -57px">
          <a-form :form="form">
            <a-form-item label="整改图片" :labelCol="labelCol_A" :wrapperCol="wrapperCol_A">
              <a-upload
                name="file"
                list-type="picture-card"
                :file-list="reformerFileList"
                :showUploadList="true"
                data-type="jpg|png|jpeg|JPG|PNG|JPEG"
                ref="Pics"
                :before-upload="beforeReformerUpload"
                @change="handleReformerPicChange"
                :remove="handleReformerRemove"
                @preview="handlePreview"
                :customRequest="customRequest"
                multiple
              >
                <div v-if="reformerShowLoader" class="spinner"></div>
                <div id="container" v-if="reformerFileList.length < 4 && !reformerShowLoader">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handlePicCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12" style="margin-top: -20px;">
          <a-form :form="form">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-radio-group v-decorator="['status']" @change="handleRadioChange">
                <a-radio value="未整改" style="margin-left: 100px">不验收</a-radio>
                <a-radio value="已整改" style="margin-left: 60px">验收</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-divider orientation="left" style="font-weight: bold;margin-top:-10px" v-show="showCheck">
        <a-icon type="check-circle" style="margin-right: 8px;color:rgb(13, 158, 243)"></a-icon> 验收信息
      </a-divider>
      <a-row :gutter="24" v-show="showCheck" style="margin-bottom:-30px">
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="验收时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-date-picker
                placeholder="选择日期"
                show-time
                :showToday="true"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="acceptTime"
                @change="handleChangeTime3"/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="18">
          <a-form :form="form">
            <a-form-item
              label="验收描述"
              :labelCol="labelCol_A"
              :wrapperCol="wrapperCol_A"
              style="width: 107.2%; margin-left: -28px"
            >
              <a-textarea
                v-decorator="['checkDescription']"
                placeholder="请输入验收描述"
                :rows="2"
                :span="40"
              />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-spin>
  </a-modal>
</template>
<script>
  import moment from 'moment'
  import Exif from 'exif-js'
  import { getQHSEOrganizationTree, getQHSELocationPage } from '@/api/modular/system/QHSEOrganization'
  import { getQHSEKeyWorkSpecialtyList, getQHSEKeyWorkTypePage, getQHSEKeyWorkContentPage } from '@/api/modular/system/QHSEKeyWork'
  import {
    getQHSEKNHGList,
    getQHSEYYFXList,
    getQHSEGSBMList,
    getQHSEHazardLevelList,
    getQHSEHazardStatusList,
    getCheckTypeList
  } from '@/api/modular/system/QHSEDictionary'
  import { getUnitTree1 } from '@/api/modular/system/violationManage'
  import { getQHSECrossDangerDetail, getQHSEDangerCategoryTree, getQHSEDangerCategoryHSE, getQHSECrossDangerEdit, getDangerClause, getDangerClauseAssocition } from '@/api/modular/system/QHSEDanger'
  import { DatePicker, TreeSelect, Select, Input, Upload } from 'ant-design-vue'
  import { STable, XCard, XDown, ChoosePeople } from '@/components'
  import { mapGetters } from 'vuex'
  function getBase64 (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }
  async function readFileAsync(file) {
    const reader = new FileReader()
    if (file.originFileObj !== undefined) {
      reader.readAsDataURL(file.originFileObj)
      return new Promise((resolve, reject) => {
        reader.onload = function () {
          const base64String = reader.result.split(',')[1]
          resolve({ name: file.name, base64Content: base64String })
        }
        reader.onerror = function () {
          reject(new Error('读取失败'))
        }
      })
    } else {
      const parts = file.url.split(',')
      const base64String = parts[1]
      return { name: file.name, base64Content: base64String }
    }
  }
  async function convertFilesToArrayAsync(files) {
    const outputArray = []
    for (const file of files) {
      const output = await readFileAsync(file)
      // 在这里对输出对象进行进一步处理或者使用
      // console.log('output----', output)
      outputArray.push(output)
    }
    return outputArray
  }
  // 异步加载图片
  function loadImageAsync(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        const image = new Image()
        image.onload = () => resolve(image)
        image.onerror = reject
        image.src = e.target.result
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    })
  }
  export default {
    components: {
      XDown,
      XCard,
      STable,
      DatePicker,
      TreeSelect,
      Select,
      Input,
      ChoosePeople,
      Upload
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        labelCol_A: {
          xs: { span: 12 },
          sm: { span: 3 }
        },
        wrapperCol_A: {
          xs: { span: 36 },
          sm: { span: 20 }
        },
        labelCol_S: {
          xs: { span: 12 },
          sm: { span: 6 }
        },
        wrapperCol_S: {
          xs: { span: 20 },
          sm: { span: 13 }
        },
        count: 1,
        visible: false,
        confirmLoading: false,
        data: [],
        replaceFields: {
          children: 'children',
          title: 'title',
          key: 'id',
          value: 'id'
        },
        secondOraName: {
          id: ''
        },
        form: this.$form.createForm(this),
        userId: '',
        directDepartment: '',
        QHSEOrganizationTree: [],
        QHSEDangerCategoryTree: [],
        QHSEKNHGList: [],
        QHSEYYFXList: [],
        QHSEGSBMList: [],
        QHSEKeyWorkSpecialtyList: [],
        KeyWorkTypeList: [],
        KeyWorkContentList: [],
        LocationList: [],
        unitTree: [],
        checkSpecialData: [],
        dtc: '',
        spc: '',
        selectedName: null,
        peopleList: [],
        Modalvisible: false,
        workSpecialtyValue: '',
        dangerTypeValue: '',
        workTypeValue: '',
        dangerCategory: '',
        organizationId: '',
        organizationName: '',
        dangerFiles: [],
        reformerFiles: [],
        previewVisible: false,
        previewImage: '',
        flag: true,
        dangerFileList: [],
        reformerFileList: [],
        HazardLevelList: [],
        HazardStatusList: [],
        dangerClauseList: [],
        showCheck: false,
        dangerShowLoader: false,
        reformerShowLoader: false,
        dangerHSEList: [],
        dangerClauseValue: '',
        checkTime: null,
        enterTime: null,
        reformTime: null,
        acceptTime: null,
        reformerUserId: null,
        contractingUnitName: '',
        contractingUnitId: '',
        fabaotree: {
          id: '00'
        }
      }
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    methods: {
      moment,
      // 关闭模态框（图片预览）
      handlePicCancel () {
        this.previewImage = ''
        this.previewVisible = false
      },
      customRequest(option) {
      },
      // 打开模态框（图片预览）
      async handlePreview (file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      // 删除隐患照片
      async handleDangerRemove (file) {
        const index = this.dangerFileList.indexOf(file)
        const newFileList = this.dangerFileList.slice()
        newFileList.splice(index, 1)
        this.dangerFileList = newFileList
        this.flag = false
        const outputArray = await convertFilesToArrayAsync(this.dangerFileList)
        // 最终得到的 outputArray 数组包含多个输出对象
        // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
        const resultArray = outputArray.map(({ name, base64Content }) => ({
          name,
          base64Content
        }))
        // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
        this.dangerFiles = resultArray
      },
      // 删除整改照片
      async handleReformerRemove (file) {
        const index = this.reformerFileList.indexOf(file)
        const newFileList = this.reformerFileList.slice()
        newFileList.splice(index, 1)
        this.reformerFileList = newFileList
        this.flag = false
        const outputArray = await convertFilesToArrayAsync(this.reformerFileList)
        // 最终得到的 outputArray 数组包含多个输出对象
        // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
        const resultArray = outputArray.map(({ name, base64Content }) => ({
          name,
          base64Content
        }))
        // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
        this.reformerFiles = resultArray
      },
      // 压缩并上传文件
      async dangerCompressAndUpload(file) {
        try {
          this.dangerShowLoader = true
          const image = await loadImageAsync(file) // 加载图片
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          // 调整图片尺寸
          const maxWidth = 800
          const maxHeight = 600
          let width = image.width
          let height = image.height
          if (width > maxWidth || height > maxHeight) {
            const ratio = Math.min(maxWidth / width, maxHeight / height)
            width *= ratio
            height *= ratio
          }
          // 根据目标文件大小调整压缩质量
          const maxSizeInBytes = 2 * 1024 * 1024 // 2MB
          let compressedFile = {}
          let quality = 0.9 // 初始压缩质量
          let compressedSize = Infinity
          // 迭代压缩直到文件大小符合要求
          while (compressedSize > maxSizeInBytes && quality > 0) {
            canvas.width = width
            canvas.height = height
            ctx.clearRect(0, 0, width, height)
            ctx.drawImage(image, 0, 0, width, height)
            // 将 canvas 转为 Blob 对象，并获取文件大小
            const blob = await new Promise((resolve) => {
              canvas.toBlob((blob) => {
                resolve(blob)
              }, file.type, quality)
            })
            compressedFile = new File([blob], file.name, {
              type: file.type,
              lastModified: Date.now()
            })
            compressedSize = compressedFile.size
            // 降低压缩质量
            quality -= 0.1
          }
          const uid = 'vc-upload-' + compressedFile.lastModified + '-' + compressedFile.name.split('.')[0]
          compressedFile.uid = uid
          this.dangerShowLoader = false
          // console.log('compressedFile', compressedFile)
          return compressedFile // 解析 Promise 并将结果传递出去
        } catch (error) {
          throw error // 如果发生错误，则将错误传递出去
        }
      },
      async reformerCompressAndUpload(file) {
        try {
          this.reformerShowLoader = true
          const image = await loadImageAsync(file) // 加载图片
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          // 调整图片尺寸
          const maxWidth = 800
          const maxHeight = 600
          let width = image.width
          let height = image.height
          if (width > maxWidth || height > maxHeight) {
            const ratio = Math.min(maxWidth / width, maxHeight / height)
            width *= ratio
            height *= ratio
          }
          // 根据目标文件大小调整压缩质量
          const maxSizeInBytes = 2 * 1024 * 1024 // 2MB
          let compressedFile = {}
          let quality = 0.9 // 初始压缩质量
          let compressedSize = Infinity
          // 迭代压缩直到文件大小符合要求
          while (compressedSize > maxSizeInBytes && quality > 0) {
            canvas.width = width
            canvas.height = height
            ctx.clearRect(0, 0, width, height)
            ctx.drawImage(image, 0, 0, width, height)
            // 将 canvas 转为 Blob 对象，并获取文件大小
            const blob = await new Promise((resolve) => {
              canvas.toBlob((blob) => {
                resolve(blob)
              }, file.type, quality)
            })
            compressedFile = new File([blob], file.name, {
              type: file.type,
              lastModified: Date.now()
            })
            compressedSize = compressedFile.size
            // 降低压缩质量
            quality -= 0.1
          }
          const uid = 'vc-upload-' + compressedFile.lastModified + '-' + compressedFile.name.split('.')[0]
          compressedFile.uid = uid
          this.reformerShowLoader = false
          // console.log('compressedFile', compressedFile)
          return compressedFile // 解析 Promise 并将结果传递出去
        } catch (error) {
          throw error // 如果发生错误，则将错误传递出去
        }
      },
      // 上传隐患图片之前的校验
      beforeDangerUpload (file) {
        const type = this.$refs.Pics.$attrs['data-type']
        return new Promise((resolve, reject) => {
          // 校验文件类型
          const exName = file.name.split('.')[1]
          if (!type.includes(exName)) {
            this.$message.error('请检查文件类型,只允许上传图片文件')
            const error = new Error('请检查文件类型，只允许上传图片文件')
            reject(error)
          } else if (file.size / 1024 / 1024 > 2) {
            // console.log('file:', file)
              this.dangerCompressAndUpload(file)
              .then((compressedFile) => {
                // 处理 compressedFile
                // console.log('compressedFile:', compressedFile)
                file = compressedFile
                // resolve(file)
              })
              .catch((error) => {
                // 处理错误
                reject(error)
              })
              // const error = new Error('上传文件大小不能超过2MB')
              // reject(error)
          }
          let picTime = false
          return new Promise((resolve, reject) => {
            Exif.getData(file, function() {
              const exifData = Exif.getAllTags(this)
              let dateTimeOriginal = exifData.DateTimeOriginal
              const dateTime = exifData.DateTime
              if (!dateTimeOriginal && dateTime) {
                dateTimeOriginal = dateTime
              }
              if (exifData && dateTimeOriginal) {
                // console.log('dateTimeOriginal', dateTimeOriginal)
                picTime = true
              } else {
                picTime = false
              }
              resolve(picTime) // 返回 picTime 的值到 Promise 的 resolve 函数
            })
          }).then(result => {
            resolve(file)
            // if (result) {
            //   // console.log('图片有拍摄时间')
            //   resolve(file)
            //   // 执行图片有拍摄时间时的操作
            // } else {
            //   this.$message.error('该图片没有拍摄时间')
            //   // console.log('图片没有拍摄时间')
            //   // 执行图片没有拍摄时间时的操作
            // }
          }).catch(error => {
            console.error(error)
          })
        })
      },
      // 上传整改图片之前的校验
      beforeReformerUpload(file) {
        const type = this.$refs.Pics.$attrs['data-type']
        return new Promise((resolve, reject) => {
          // 校验文件类型
          const exName = file.name.split('.')[1]
          if (!type.includes(exName)) {
            this.$message.error('请检查文件类型,只允许上传图片文件')
            const error = new Error('请检查文件类型，只允许上传图片文件')
            reject(error)
          } else if (file.size / 1024 / 1024 > 2) {
            // console.log('file:', file)
              this.reformerCompressAndUpload(file)
              .then((compressedFile) => {
                // 处理 compressedFile
                // console.log('compressedFile:', compressedFile)
                file = compressedFile
                // resolve(file)
              })
              .catch((error) => {
                // 处理错误
                reject(error)
              })
              // const error = new Error('上传文件大小不能超过2MB')
              // reject(error)
          }
          let picTime = false
          return new Promise((resolve, reject) => {
            Exif.getData(file, function() {
              const exifData = Exif.getAllTags(this)
              let dateTimeOriginal = exifData.DateTimeOriginal
              const dateTime = exifData.DateTime
              if (!dateTimeOriginal && dateTime) {
                dateTimeOriginal = dateTime
              }
              if (exifData && dateTimeOriginal) {
                console.log('dateTimeOriginal', dateTimeOriginal)
                picTime = true
              } else {
                picTime = false
              }
              resolve(picTime) // 返回 picTime 的值到 Promise 的 resolve 函数
            })
          }).then(result => {
            resolve(file)
            // if (result) {
            //   // console.log('图片有拍摄时间')
            //   resolve(file)
            //   // 执行图片有拍摄时间时的操作
            // } else {
            //   this.$message.error('该图片没有拍摄时间')
            //   // console.log('图片没有拍摄时间')
            //   // 执行图片没有拍摄时间时的操作
            // }
          }).catch(error => {
            console.error(error)
          })
        })
      },
      // 上传隐患图片方法
      async handleDangerPicChange (file) {
        // 当删除的时候会触发onchange事件 因此使用flag控制onchange事件
        if (this.dangerFileList.length >= 4) {
          this.$message.warning('最多只能选择4张图片')
        }
        if (this.flag === true) {
          file.file.status = 'done'
          const formData = new FormData()
          formData.append('file', file.file)
          // console.log('file123', file)
          this.dangerFileList = file.fileList
          // 假设 this.dangerFileList 是包含多个文件对象的数组
          const outputArray = await convertFilesToArrayAsync(this.dangerFileList)
          // 最终得到的 outputArray 数组包含多个输出对象
          // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
          const resultArray = outputArray.map(({ name, base64Content }) => ({
            name,
            base64Content
          }))
          this.dangerFiles = resultArray
          // const last = resultArray[resultArray.length - 1]
          // danComparePic(last).then(res => {
          //   // console.log(res.data)
          //   if (res.data) {
          //     this.$message.error('图片重复')
          //     this.dangerFileList.pop()
          //   } else {
          //     // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
          //     this.dangerFiles = resultArray
          //   }
          // })
        } else {
          this.flag = true
        }
      },
      // 上传整改图片方法
      async handleReformerPicChange (file) {
        // 当删除的时候会触发onchange事件 因此使用flag控制onchange事件
        if (this.reformerFileList.length >= 4) {
          this.$message.warning('最多只能选择4张图片')
        }
        if (this.flag === true) {
          file.file.status = 'done'
          const formData = new FormData()
          formData.append('file', file.file)
          // console.log('file456', file)
          this.reformerFileList = file.fileList
          // 假设 this.reformerFileList 是包含多个文件对象的数组
          const outputArray = await convertFilesToArrayAsync(this.reformerFileList)
          // 最终得到的 outputArray 数组包含多个输出对象
          // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
          const resultArray = outputArray.map(({ name, base64Content }) => ({
            name,
            base64Content
          }))
          this.reformerFiles = resultArray
          // const last = resultArray[resultArray.length - 1]
          // danComparePic(last).then(res => {
          //   // console.log(res.data)
          //   if (res.data) {
          //     this.$message.error('图片重复')
          //     this.reformerFileList.pop()
          //   } else {
          //     // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
          //     this.reformerFiles = resultArray
          //   }
          // })
        } else {
          this.flag = true
        }
        // console.log('this.reformerFileList.length', this.reformerFileList.length)
      },
      showModal() {
        this.Modalvisible = true
      },
      getQHSEKNHGList(text) {
        getQHSEKNHGList().then((res) => {
          this.QHSEKNHGList = res.data
        })
      },
      getQHSEGSBMList(text) {
        getQHSEGSBMList().then((res) => {
          this.QHSEGSBMList = res.data
        })
      },
      getQHSEYYFXList(text) {
        getQHSEYYFXList().then((res) => {
          this.QHSEYYFXList = res.data
        })
      },
      getQHSEHazardLevelList(text) {
        getQHSEHazardLevelList().then((res) => {
          this.HazardLevelList = res.data
          // const option = this.HazardLevelList.find((opt) => opt.item === this.dangerTypeValue)
          // const option2 = this.QHSEKeyWorkSpecialtyList.find((opt) => opt.specialty === this.workSpecialtyValue)
          // if (option !== undefined) {
          //   this.dtc = option.code
          //   const rvtcv = this.form.getFieldValue('dangerTypeCategory')
          //   if (rvtcv === '专业隐患') {
          //     this.spc = option2.specialtyCode
          //     console.log('spc:', this.spc)
          //     if (this.spc && this.dtc) {
          //       getQHSESpecialtyDanger({ 'DangerTypeCode': this.dtc, 'SpecialtyCode': this.spc }).then(res => {
          //         this.dangerClauseList = res.data.rows
          //       })
          //     } else {
          //       this.form.setFieldsValue({ dangerClause: '' })
          //       this.dangerClauseList = []
          //     }
          //   } else if (rvtcv === '通用隐患') {
          //     getQHSEGeneralDanger({ 'DangerTypeCode': this.dtc }).then(res => {
          //       this.dangerClauseList = res.data.rows
          //     })
          //   } else {
          //     this.dangerClauseList = []
          //   }
          // }
        })
      },
      getQHSEHazardStatusList(text) {
        getQHSEHazardStatusList().then((res) => {
          this.HazardStatusList = res.data
        })
      },
      getQHSEKeyWorkSpecialtyList(text) {
        getQHSEKeyWorkSpecialtyList().then((res) => {
          this.QHSEKeyWorkSpecialtyList = res.data
          const option = this.QHSEKeyWorkSpecialtyList.find((opt) => opt.specialty === this.workSpecialtyValue)
          if (option !== undefined) {
            getQHSEKeyWorkTypePage({ 'code': option.specialtyCode }).then(res => {
              this.KeyWorkTypeList = res.data.rows
              const value = this.form.getFieldValue('workType')
              if (value !== null && value !== undefined) {
                const option2 = this.KeyWorkTypeList.find((opt) => opt.workType === this.workTypeValue)
                if (option2 !== undefined) {
                  console.log('option2', option2)
                  getQHSEKeyWorkContentPage({ 'code': option2.workTypeCode }).then(res => {
                    this.KeyWorkContentList = res.data.rows
                  })
                }
              }
            })
            getQHSELocationPage({ 'code': option.specialtyCode }).then(res => {
              this.LocationList = res.data.rows
            })
            this.spc = option.specialtyCode
          }
        })
      },
      getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('tree:', res.data)
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.QHSEOrganizationTree = res.data
        })
      },
      getQHSEDangerCategoryTree() {
        getQHSEDangerCategoryTree().then((res) => {
          this.formLoading = false
          if (!res.success) {
            this.QHSEDangerCategoryTree = []
            return
          }
          this.QHSEDangerCategoryTree = res.data
        })
      },
      getDangerClause() {
        getDangerClause().then((res) => {
          // console.log('dangerClauseList:', res.data)
          this.dangerClauseList = res.data
          const option = this.dangerClauseList.find((opt) => opt.description === this.dangerClauseValue)
          // console.log('option:', option)
          if (option !== undefined) {
            getDangerClauseAssocition({ 'id': option.generalSpecialtyId }).then(res => {
              if (res.data !== null) {
                this.dangerHSEList = res.data.hse ? res.data.hse : []
              }
            })
          }
        })
      },
      getCheckTypeList() {
        getCheckTypeList().then(res => {
            this.checkSpecialData = res.data
            // console.log(this.checkSpecialData)
        })
      },
      handleChangeTime(time, timeString) {
        const enterDate = moment(this.enterTime, 'YYYY-MM-DD HH:mm:ss')
        const differenceInDays = enterDate.diff(time, 'days')
        const differenceInSeconds = enterDate.diff(time, 'seconds')
        if (differenceInSeconds < 0) {
          this.$message.warning('检查时间不能晚于录入时间')
          this.checkTime = enterDate.subtract(1, 'seconds')
          this.form.setFieldsValue({ 'checkDate': this.checkTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T') })
        } else if (differenceInDays > this.$constants.timeInterval) {
          this.$message.warning('检查时间与录入时间不能超过' + this.$constants.timeInterval + '天')
          this.checkTime = enterDate.subtract(1, 'seconds')
          this.form.setFieldsValue({ 'checkDate': this.checkTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T') })
        } else {
          this.form.setFieldsValue({ 'checkDate': timeString.replace(' ', 'T') })
        }
      },
      handleChangeTime2(time, timeString) {
        const checkDate = moment(this.form.getFieldValue('checkDate'), 'YYYY-MM-DD HH:mm:ss')
        const differenceInDays = checkDate.diff(time)
        if (differenceInDays > 0) {
          this.$message.warning('限期整改时间不能早于检查时间')
          this.reformTime = checkDate.add(1, 'seconds')
          this.form.setFieldsValue({ 'reformerDate': this.reformTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T') })
        } else {
          this.form.setFieldsValue({ 'reformerDate': timeString.replace(' ', 'T') })
        }
      },
      handlefbOrganizationSelectChange(val, opt, extra) {
        // console.log('extra', extra)
        if (extra.triggerNode === undefined) {
          this.contractingUnitName = ''
          this.contractingUnitId = ''
        } else {
          if (extra.triggerNode._props.dataRef.children.length === 0) {
            const value = extra.triggerNode._props.dataRef.id
            const option = extra.triggerNode._props.title
            this.contractingUnitName = option
            this.contractingUnitId = value
          } else {
            this.contractingUnitName = ''
            this.contractingUnitId = ''
            this.$message.error('非正确节点，请重新选择！')
          }
        }
        // console.log(this.contractingUnitName)
      },
      handleChangeTime3(time, timeString) {
        const checkDate = moment(this.form.getFieldValue('checkDate'), 'YYYY-MM-DD HH:mm:ss')
        const differenceInDays = checkDate.diff(time)
        if (differenceInDays > 0) {
          this.$message.warning('限期整改时间不能早于检查时间')
          this.acceptTime = checkDate.add(1, 'seconds')
          this.form.setFieldsValue({ 'acceptanceDate': this.acceptTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T') })
        } else {
          this.form.setFieldsValue({ 'acceptanceDate': timeString.replace(' ', 'T') })
        }
      },
      handleZYZYSelectChange(value, option) {
        this.form.setFieldsValue({
          workType: '',
          location: '',
          workContent: '',
          workRisk: ''
        })
        this.KeyWorkContentList = []
        this.spc = ''
        if (option) {
          getQHSEKeyWorkTypePage({ 'code': option.data.attrs.code }).then(res => {
            this.KeyWorkTypeList = res.data.rows
          })
          getQHSELocationPage({ 'code': option.data.attrs.code }).then(res => {
            this.LocationList = res.data.rows
          })
          this.spc = option.data.attrs.code
          this.form.setFieldsValue({ workSpecialtyCode: option.data.attrs.code })
        }
        // const rvtcv = this.form.getFieldValue('dangerTypeCategory')
        // if (rvtcv === '专业隐患') {
        //   if (this.spc && this.dtc) {
        //     getQHSESpecialtyDanger({ 'DangerTypeCode': this.dtc, 'SpecialtyCode': this.spc }).then(res => {
        //       this.dangerClauseList = res.data.rows
        //       this.form.setFieldsValue({ dangerClause: '' })
        //     })
        //   } else {
        //     this.form.setFieldsValue({ dangerClause: '' })
        //     this.dangerClauseList = []
        //   }
        // }
      },
      handleKeyWorkTypeSelectChange(value, option) {
        this.form.setFieldsValue({
          workContent: '',
          workRisk: ''
        })
        if (option) {
          this.form.setFieldsValue({ keyWorkCode: option.data.attrs.code })
          getQHSEKeyWorkContentPage({ 'code': option.data.attrs.code }).then(res => {
            this.KeyWorkContentList = res.data.rows
          })
        }
      },
      handleKeyWorkContentSelectChange(value, option) {
        if (option) {
          this.form.setFieldsValue({ workRisk: option.data.attrs.rk })
        }
      },
      handleDangerTypeSelectChange(value, option) {
        if (option) {
          this.form.setFieldsValue({ dangerTypeCode: option.data.attrs.dtc })
        }
        // this.form.setFieldsValue({
        //   dangerClause: ''
        // })
        // const rvtcv = this.form.getFieldValue('dangerTypeCategory')
        // if (option) {
        //   this.dtc = option.data.attrs.dtc
        // }
        // if (rvtcv === '通用隐患') {
        //   getQHSEGeneralDanger({ 'DangerTypeCode': this.dtc }).then(res => {
        //     this.dangerClauseList = res.data.rows
        //   })
        // } else if (rvtcv === '专业隐患' && this.spc) {
        //   getQHSESpecialtyDanger({ 'DangerTypeCode': this.dtc, 'SpecialtyCode': this.spc }).then(res => {
        //     this.dangerClauseList = res.data.rows
        //   })
        // } else {
        //   this.dangerClauseList = []
        // }
      },
      handleDangerCategorySelectChange(val, opt, extra) {
        // console.log(extra)
        if (extra.triggerNode === undefined) {
          this.form.setFieldsValue({ hseElement: '' })
          this.form.setFieldsValue({ hseCode: '' })
        } else {
          if (extra.triggerNode._props.dataRef.children.length === 0) {
            const value = extra.triggerNode._props.dataRef.id
            const option = extra.triggerNode._props.title
            if (value) {
              this.dangerCategory = option
              this.form.setFieldsValue({ dangerCateId: value })
              getQHSEDangerCategoryHSE({ 'id': value }).then(res => {
                this.form.setFieldsValue({ hseElement: res.data.result[0].item })
                this.form.setFieldsValue({ hseCode: res.data.result[0].code })
                this.dangerHSEList = res.data.result
              })
            }
          } else {
            this.dangerCategory = ''
            this.form.setFieldsValue({ hseElement: '' })
            this.form.setFieldsValue({ hseCode: '' })
            this.$message.error('非正确节点，请重新选择！')
          }
        }
      },
      handleOrganizationSelectChange(val, opt, extra) {
        if (extra.triggerNode === undefined) {
          this.organizationName = ''
          this.organizationId = ''
        } else {
          if (extra.triggerNode._props.dataRef.children.length === 0) {
            const value = extra.triggerNode._props.dataRef.id
            const option = extra.triggerNode._props.title
            this.organizationName = option
            this.organizationId = value
          } else {
            this.organizationName = ''
            this.organizationId = ''
            this.$message.error('非正确节点，请重新选择！')
          }
        }
      },
      handleDangerRadioChange(val, opt, extra) {
        // this.form.setFieldsValue({ dangerClause: '' })
        // if (this.dtc) {
        //   if (val.target.value === '通用隐患') {
        //     getQHSEGeneralDanger({ 'DangerTypeCode': this.dtc }).then(res => {
        //       this.dangerClauseList = res.data.rows
        //     })
        //   } else if (val.target.value === '专业隐患' && this.spc) {
        //     getQHSESpecialtyDanger({ 'DangerTypeCode': this.dtc, 'SpecialtyCode': this.spc }).then(res => {
        //       this.dangerClauseList = res.data.rows
        //     })
        //   } else {
        //     this.dangerClauseList = []
        //   }
        // } else {
        //   this.dangerClauseList = []
        // }
      },
      handleRadioChange(val, opt, extra) {
        // console.log(val, opt, extra)
        if (val.target.value === '未整改') {
          this.showCheck = false
        } else {
          this.showCheck = true
        }
      },
      chooseDangerClause(item) {
        this.form.setFieldsValue({ dangerClause: item.description })
        this.form.setFieldsValue({ description: item.description })
        const chooseWorkClauseCode = item.generalSpecialtyId
        getDangerClauseAssocition({ 'id': chooseWorkClauseCode }).then(res => {
          if (res.data !== null) {
            this.dangerCategory = res.data.dangerCategory
            this.dangerHSEList = res.data.hse
            this.form.setFieldsValue({
              dangerType: res.data.dangerType,
              dangerTypeCode: res.data.dangerTypeCode,
              dangerTypeCategory: res.data.dangerTypeCategory,
              hseElement: res.data.hse[0].item,
              hseCode: res.data.hse[0].code
            })
          }
        })
      },
      chooseHse(item) {
        if (item) {
          this.form.setFieldsValue({ hseCode: item.code })
        }
        // console.log('hse:', item)
      },
      chooseDepart(item) {
        if (item) {
          this.form.setFieldsValue({ departmentCode: item.code })
        }
        // console.log('depart:', item)
      },
      chooseCause(item) {
        if (item) {
          this.form.setFieldsValue({ clauseAnalysisCode: item.code })
        }
        // console.log('cause:', item)
      },
      choosecheckSpecialty(item) {
        if (item) {
          this.form.setFieldsValue({ checkTypeCode: item.code })
        }
      },
      getQHSECrossDangerDetail(text) {
        getQHSECrossDangerDetail(text).then((res) => {
          // console.log('res:', res)
          // setTimeout(() => {
          this.form.setFieldsValue({
            // 违章ID
            qhseXyDangerId: res.data.qhseXyDangerId,
            // 检查人员ID
            userId: res.data.userId,
            // 检查人员姓名
            checkName: res.data.checkName,
            // 检查时间
            checkDate: res.data.checkDate,
            // 录入时间
            enterTime: res.data.enterTime ? res.data.enterTime : undefined,
            // 数据来源
            enterSys: res.data.enterSys,
            // 检查类型
            checkType: res.data.checkType,
            // 作业项目
            workItem: res.data.workItem,
            // 关键作业内容
            workContent: res.data.workContent,
            // 作业风险等级
            workRisk: res.data.workRisk,
            // 关键作业类型
            workType: res.data.workType,
            // 作业专业
            workSpecialty: res.data.workSpecialty,
            // 位置区域
            location: res.data.location,
            // 隐患性质分类
            dangerTypeCategory: res.data.dangerTypeCategory,
            // 隐患级别
            dangerType: res.data.dangerType,
            // 隐患条款
            dangerClause: res.data.dangerClause,
            // 隐患描述
            description: res.data.description,
            // 体系要素
            hseElement: res.data.hseElement,
            // 安全沟通
            observeComm: res.data.observeComm,
            // 原因分析
            causeAnalysis: res.data.causeAnalysis,
            // 归属直线部门
            directDepartment: res.data.directDepartment,
            // 可能后果
            potentialConsequence: res.data.potentialConsequence,
            // 整改人员ID
            reformerUserId: res.data.reformerUserId,
            // 整改人员姓名
            reformerUserName: res.data.reformerUserName,
            // 整改限期
            reformerDate: res.data.reformerDate,
            // 验收状态
            status: res.data.status,
            // 验收时间
            acceptanceDate: res.data.acceptanceDate,
            // 验收描述
            checkDescription: res.data.checkDescription,
            // 图片（不用）
            dangerPic: res.data.dangerPic,
            reformerPic: res.data.reformerPic,
            // 隐患类别树id
            dangerCateId: res.data.dangerCateId,
            // 检查类型code
            checkTypeCode: res.data.checkTypeCode,
            // 关键作业类型code
            keyWorkCode: res.data.keyWorkCode,
            // 作业专业code
            workSpecialtyCode: res.data.workSpecialtyCode,
            // 隐患级别code
            dangerTypeCode: res.data.dangerTypeCode,
            // 对应体系要素code
            hseCode: res.data.hseCode,
            // 归属部门code
            departmentCode: res.data.departmentCode,
            // 原因分析code
            clauseAnalysisCode: res.data.clauseAnalysisCode,
            // 人员的检查单位id
            checkOrganizationId: res.data.checkOrganizationId,
            // 隐患所属公司
            relatedCompany: res.data.relatedCompany
          })
          // }, 1)
          this.userId = res.data.userId
          this.directDepartment = res.data.directDepartment
          this.workSpecialtyValue = this.form.getFieldValue('workSpecialty')
          this.dangerTypeValue = this.form.getFieldValue('dangerType')
          this.workTypeValue = this.form.getFieldValue('workType')
          this.dangerClauseValue = this.form.getFieldValue('dangerClause')
          this.checkTime = moment(this.form.getFieldValue('checkDate'))
          this.reformTime = moment(this.form.getFieldValue('reformerDate'))
          this.acceptTime = moment(this.form.getFieldValue('acceptanceDate'))
          this.enterTime = this.form.getFieldValue('enterTime') ? this.form.getFieldValue('enterTime').replace('T', ' ') : undefined
          this.reformerUserId = this.form.getFieldValue('reformerUserId')
          // 隐患类别
          this.dangerCategory = res.data.dangerCategory
          this.contractingUnitName = res.data.contractingUnitName
          this.contractingUnitId = res.data.contractingUnitId
          // 被检查单位id
          this.organizationId = res.data.organizationId
          // 被检查单位名称
          this.organizationName = res.data.organizationName
          this.dangerFiles = res.data.dangerFiles
          this.reformerFiles = res.data.reformerFiles
          if (res.data.status === '已整改') {
            this.showCheck = true
          } else {
            this.showCheck = false
          }
          // 在组件创建时，将 files 数组转换为 uploadFileList 数组
          this.dangerFileList = this.dangerFiles.map((file, index) => {
            const suffix = file.name.split('.').pop()
            return {
              uid: `file-${index}`,
              name: file.name,
              status: 'done',
              url: `data:image/${suffix};base64,${file.base64Content}`,
              thumbUrl: ''
            }
          })
          this.reformerFileList = this.reformerFiles.map((file, index) => {
            const suffix = file.name.split('.').pop()
            return {
              uid: `file-${index}`,
              name: file.name,
              status: 'done',
              url: `data:image/${suffix};base64,${file.base64Content}`,
              thumbUrl: ''
            }
          })
          return res.data
        })
      },
      queryDetail(record) {
        const param = { 'id': record.qhseXyDangerId }
        this.getQHSECrossDangerDetail(param)
      },
      // 初始化方法
      edit(record) {
        this.queryDetail(record)
        // console.log('--this is record from edit--', record)
        this.confirmLoading = true
        this.visible = true
        this.getCheckTypeList()
        this.getQHSEOrganizationTree()
        this.getQHSEDangerCategoryTree()
        this.getQHSEGSBMList()
        this.getQHSEKNHGList()
        this.getQHSEYYFXList()
        this.getQHSEKeyWorkSpecialtyList()
        this.getQHSEHazardLevelList()
        this.getQHSEHazardStatusList()
        this.getDangerClause()
        this.getUnitTree()
        // 基本信息加人表单
        this.confirmLoading = false
      },
      getUnitTree() {
          // console.log(this.secondOraName)
          getUnitTree1(Object.assign(this.fabaotree)).then(res => {
            this.treeLoading = false
            this.unitTree = res.data
            // console.log('unitTree', this.unitTree)
          })
          // this.visible = false
        },
      handleSubmit() {
        const {
          form: { validateFields }
        } = this
        this.confirmLoading = true
        validateFields(async(errors, values) => {
          if (!errors && this.dangerCategory && typeof this.dangerCategory !== 'undefined' && this.dangerCategory !== '' &&
            this.organizationId && typeof this.organizationId !== 'undefined' && this.organizationId !== '' && this.organizationName && typeof this.organizationName !== 'undefined' && this.organizationName !== '' &&
            this.contractingUnitName !== '' && typeof this.contractingUnitName !== 'undefined' &&
            this.contractingUnitId !== '' && typeof this.contractingUnitId !== 'undefined') {
            values.dangerCategory = this.dangerCategory
            values.organizationId = this.organizationId
            values.organizationName = this.organizationName
            values.dangerFiles = this.dangerFiles
            values.reformerFiles = this.reformerFiles
            values.contractingUnitName = this.contractingUnitName
            values.contractingUnitId = this.contractingUnitId
            values.updataTime = moment().format('YYYY-MM-DDTHH:mm:ss')
            values.updateBy = this.userInfo.realName
            values.userId = this.userId
            values.directDepartment = this.directDepartment
            values.checkDate = this.checkTime
            console.log('values', values)
            getQHSECrossDangerEdit(values)
              .then((res) => {
                if (res.success && res.code === 200) {
                  this.$message.success('编辑成功')
                  this.confirmLoading = false
                  this.$emit('ok', values)
                  this.handleCancel()
                } else {
                  this.$message.error('编辑失败：' + res.message)
                }
              })
              .finally((res) => {
                this.confirmLoading = false
              })
          } else {
            // console.log('values', values)
            this.confirmLoading = false
            this.$message.warning('信息尚未完善，请完善后提交')
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.reformerUserId = null
        this.visible = false
        // 清理子表单中数据
        this.data = []
      },
      handleModalCancel() {
        this.Modalvisible = false
      },
      chooseVioPeople(userName, userId, userDeptId) {
        // console.log('收到了username=' + userName)
        // console.log('收到了userid=' + userId)
        // console.log('收到了unitname=' + userDeptId)
        this.form.setFieldsValue({
          reformerUserName: userName,
          reformerUserId: userId
        })
        this.reformerUserId = userId
        this.Modalvisible = false
      }
    }
  }
</script>
<style scoped>
  *[disabled] {
    color: black;
    background-color: whitesmoke;
    cursor: not-allowed;
    opacity: 0.5;
  }
  .spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 48px;
    height: 48px;
    animation: spin 2s linear infinite;
    margin: 20px auto;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
</style>
